<template>
  <v-card>
    <v-toolbar flat color="blue" dark height="50">
      <v-spacer></v-spacer>
      <v-toolbar-title>设置【 {{ user_info.username }} 】</v-toolbar-title>
      <v-spacer></v-spacer>
    </v-toolbar>
    <v-tabs vertical>
      <v-tab>
        <v-icon left> mdi-account </v-icon>
        个人信息
      </v-tab>
      <v-tab>
        <v-icon left> mdi-lock </v-icon>
        账户设置
      </v-tab>

      <!-- 个人信息tab内容 -->
      <v-tab-item>
        <v-card flat>
          <v-container fluid>
            <!-- 更改头像 -->
            <v-container fill-height>
              <v-avatar class="mr-5" size="43">
                <img :src="user_info.avatar" alt="John" />
              </v-avatar>
              <v-text-field
                class="mr-3"
                hide-details="auto"
                label="头像图片链接，链接为空或无效时，将使用默认头像"
                placeholder="头像图片链接，链接为空或无效时，将使用默认头像"
                v-model="user_info.avatar"
              ></v-text-field>
            </v-container>
            <!-- 真实姓名 -->
            <v-container fill-height class="mb-7">
              <v-avatar class="mr-5" size="43"> </v-avatar>
              <v-text-field
                class="mr-3"
                hide-details="auto"
                label="真实姓名"
                placeholder="真实姓名"
                v-model="user_info.full_name"
              ></v-text-field>
            </v-container>
            <!-- 性别 -->
            <v-container fill-height class="mb-7">
              <v-avatar class="mr-5" size="43"> </v-avatar>
              <v-text-field
                class="mr-3"
                hide-details="auto"
                label="性别"
                placeholder="性别"
                v-model="user_info.gender"
              ></v-text-field>
            </v-container>
            <!-- 个人简介 -->
            <v-container fill-height>
              <!-- 空头像用于对齐 -->
              <v-avatar class="mr-5" size="43"></v-avatar>
              <v-textarea
                class="mr-3"
                counter="200"
                label="个人简介"
                :rules="user_info.desc.rules"
                v-model="user_info.desc.value"
                outlined
                auto-grow
              ></v-textarea>
            </v-container>
            <!-- 爱好 -->
            <v-container fill-height>
              <v-avatar class="mr-5" size="43"> </v-avatar>
              <v-text-field
                class="mr-3"
                hide-details="auto"
                label="爱好"
                placeholder="爱好"
                v-model="user_info.favourite"
              ></v-text-field>
            </v-container>
            <!-- 学院 -->
            <v-container fill-height>
              <v-avatar class="mr-5" size="43"> </v-avatar>
              <v-text-field
                class="mr-3"
                hide-details="auto"
                label="学院"
                placeholder="学院"
                v-model="user_info.school"
              ></v-text-field>
            </v-container>
            <!-- 专业 -->
            <v-container fill-height>
              <v-avatar class="mr-5" size="43"> </v-avatar>
              <v-text-field
                class="mr-3"
                hide-details="auto"
                label="专业"
                placeholder="专业"
                v-model="user_info.major"
              ></v-text-field>
            </v-container>
            <!-- 提示信息 -->
            <v-container v-if="error.info.show" fill-height
              ><v-avatar class="mr-5" size="43"> </v-avatar>
              <v-alert class="mt-3" dense outlined type="success">
                {{ error.info.msg }}
              </v-alert>
            </v-container>
            <!-- 保存按钮 -->
            <v-container fill-height>
              <!-- 空头像用于对齐 -->
              <v-avatar class="mr-5" size="43"></v-avatar>
              <v-btn
                @click="saveUserInfo"
                color="blue"
                text
                outlined
                :disabled="user_info.desc.value.length > 200 ? true : false"
                >保存</v-btn
              >
            </v-container>
          </v-container>
        </v-card>
      </v-tab-item>
      <!-- 账户设置tab内容 -->
      <v-tab-item>
        <v-card flat>
          <v-container fluid>
            <validation-observer ref="observer" v-slot="{ invalid }">
              <!-- 邮箱（不可更改） -->
              <v-text-field
                v-model="user_info.email"
                label="邮箱"
                disabled
              ></v-text-field>
              <!-- 旧密码 -->
              <v-text-field
                v-model="user_info.old_password"
                type="password"
                label="旧密码"
              ></v-text-field>
              <!-- 新密码 -->
              <validation-provider
                v-slot="{ errors }"
                name="新密码"
                :rules="{
                  required: true,
                  max: 16,
                  min: 8,
                  regex_password:
                    '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$',
                }"
              >
                <v-text-field
                  v-model="user_info.new_password"
                  :append-icon="
                    user_info.showPassword ? 'mdi-eye' : 'mdi-eye-off'
                  "
                  :type="user_info.showPassword ? 'text' : 'password'"
                  label="新密码(必须且只能包含字母和数字)"
                  hint="密码为8到16位"
                  :error-messages="errors"
                  counter="16"
                  @click:append="
                    user_info.showPassword = !user_info.showPassword
                  "
                ></v-text-field>
              </validation-provider>
              <!-- 提示信息 -->
              <v-container v-if="error.account.show" fill-height>
                <v-alert class="mt-3" dense outlined :type="error.account.type">
                  {{ error.account.msg }}
                </v-alert>
              </v-container>
              <!-- 按钮 -->
              <div class="my-4">
                <!-- 保存密码 -->
                <v-btn
                  @click="saveAccountSettings"
                  color="blue"
                  text
                  outlined
                  :disabled="invalid"
                  >保存</v-btn
                >
                <!-- 删除账户 -->
                <v-dialog v-model="dialog" width="500">
                  <template v-slot:activator="{ on, attrs }">
                    <v-btn
                      class="ml-5"
                      @click="dialog = true"
                      color="red"
                      dark
                      v-bind="attrs"
                      v-on="on"
                      >注销账号</v-btn
                    >
                  </template>
                  <v-card>
                    <v-card-title class="text-h5 red lighten-2 white--text">
                      您确定要注销账号吗？
                    </v-card-title>
                    <v-card-text class="mt-5">
                      注销账号之后，您的所有数据都将被删除，且无法恢复！
                    </v-card-text>
                    <v-divider></v-divider>
                    <v-card-actions>
                      <v-spacer></v-spacer>
                      <v-btn color="red" text @click="deleteAccount">
                        确认注销
                      </v-btn>
                    </v-card-actions>
                  </v-card>
                </v-dialog>
              </div>
            </validation-observer>
          </v-container>
        </v-card>
      </v-tab-item>
    </v-tabs>
  </v-card>
</template>

<script>
import { required, email, max, min, regex } from "vee-validate/dist/rules";
import {
  extend,
  ValidationObserver,
  ValidationProvider,
  setInteractionMode,
} from "vee-validate";
import { mapGetters, mapActions } from "vuex";

setInteractionMode("eager");

extend("required", {
  ...required,
  message: "{_field_}不能为空",
});

extend("max", {
  ...max,
  message: "{_field_}不能超过{length}个字符",
});

extend("min", {
  ...min,
  message: "{_field_}至少为{length}个字符",
});

extend("regex_username", {
  ...regex,
  message: "用户名不符合要求",
});

extend("regex_password", {
  ...regex,
  message: "密码必须且只能包含字母和数字",
});

extend("email", {
  ...email,
  message: "邮箱格式不正确",
});

export default {
  name: "Setting",
  components: {
    ValidationProvider,
    ValidationObserver,
  },
  data: () => ({
    // 用户个人信息
    user_info: {
      username: "",
      old_password: "",
      new_password: "",
      showPassword: false,
      full_name: "",
      email: "",
      school: "",
      major: "",
      avatar: "",
      favourite: "",
      desc: {
        rules: [(v) => v.length <= 200 || "最多输入200字"],
        value: "",
      },
      gender: "",
    },
    // 对话框
    dialog: false,
    // 提示
    error: {
      info: { show: false, msg: "" },
      account: { show: false, msg: "", type: "" },
    },
  }),
  computed: {
    ...mapGetters({ user: "stateUser", authenticated: "isAuthenticated" }),
  },
  methods: {
    ...mapActions(["updateUserInfo", "resetPassword", "destroyUser"]),
    // 保存个人信息
    async saveUserInfo() {
      let info = JSON.parse(JSON.stringify(this.user_info));
      info.desc = this.user_info.desc.value;
      await this.updateUserInfo(info);
      this.error.info.msg = "保存成功";
      this.error.info.show = true;
      setTimeout(() => {
        this.error.info.show = false;
      }, 3000);
    },
    // 保存账号信息（修改密码）
    async saveAccountSettings() {
      let err = await this.resetPassword({
        old_pwd: this.user_info.old_password,
        new_pwd: this.user_info.new_password,
        new_pwd_confirmation: this.user_info.new_password,
      });
      if (err === 15) {
        this.error.account.msg = "旧密码不正确";
        this.error.account.type = "error";
      } else {
        this.error.account.msg = "更改成功";
        this.error.account.type = "success";
      }
      this.error.account.show = true;
      setTimeout(() => {
        this.error.account.show = false;
      }, 3000);
      this.user_info.old_password = "";
    },
    // 删除账户
    async deleteAccount() {
      await this.destroyUser();
      this.dialog = false;
      this.$router.push("/auth");
    },
  },
  // 渲染前加载用户信息
  beforeMount() {
    this.user_info.username = this.user.username;
    this.user_info.full_name = this.user.full_name;
    this.user_info.email = this.user.email;
    this.user_info.school = this.user.school;
    this.user_info.major = this.user.major;
    this.user_info.avatar = this.user.avatar;
    this.user_info.favourite = this.user.favourite;
    this.user_info.desc.value = this.user.desc;
    this.user_info.gender = this.user.gender;
  },
};
</script>

<style>
</style>